package ${package.Security};

import org.apache.tomcat.util.codec.binary.Base64;
import ${package.Stereotype}.security.bean.AbstractKeyPair;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

@Component
public class KeyPair extends AbstractKeyPair {

    private String publicKey = "${publicKey}";
    private String privateKey = "${privateKey}";

    @Override
    public String getPublicKey() {
        return publicKey;
    }

    @Override
    public String getPrivateKey() {
        return privateKey;
    }

    public static void main(String[] args) throws Exception{
        KeyPair keyPair = new KeyPair();
        // 密码
        String presentedPassword = "123456";
        System.out.println("原始密码  presentedPassword = " + presentedPassword);
        byte[] decoded = Base64.decodeBase64(keyPair.getPublicKey());
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        // 前端加密后的密码
        String webPassword = Base64.encodeBase64String(cipher.doFinal(presentedPassword.getBytes("UTF-8")));
        System.out.println("前端加密后  webPassword = " + webPassword);
        PasswordEncoder encode  = new BCryptPasswordEncoder();
        // 数据库里面保存的密码
        String databasePassword = encode.encode(presentedPassword);
        System.out.println("数据库保存  databasePassword = " + databasePassword);
    }
}